// 组织结构
// ---------------------------------------------------------------------
isc.TreeGrid.create({//部门树
	ID:"depTree",dataSource:"depDS",fetchOperation:"myTreeFetch",canEdit: true,leaveScrollbarGap:false,
	animateFolders:true,showHeader:false,selectionType:"single",autoFetchData: true,animateRowsMaxTime:750
    ,cellContextClick:"return depTreeMenu.showContextMenu()"
	,rowClick: "userList.filterData({dep_pk:record.pk})",
	dataArrived:function(parentNode){
		if(!parentNode.pk){
			this.openFolder(parentNode.children[0]);
		}
	},
    fields: [{name: "name"}]
});

isc.Menu.create({//部门编辑右键目录
	ID:"depTreeMenu",
    cellHeight:22,
	data:[
        {title:"新增",
			icon:"icon_add.png",
            click:function () {
            	var p = depTree.getSelectedRecord();
            	depTree.data.openFolder(p);
            	
            	//生成新pk
            	var maxPk = 0;
            	var c =  depTree.data.getChildren(p);
            	for(var i =0; i < c.getLength(); i++){
            		var pk = Number(c.get(i).pk);
            		if(pk > maxPk){
            			maxPk = pk;
            		}
            	}
            	maxPk =""+ (maxPk +1001);
            	maxPk = maxPk.substr(1);
            	
            	//增加数据
            	var n = {pk: p.pk+maxPk,name:"新部门",corp_sid:currUserCorpSid, parentID:p.pk,orderby:0,isFolder:false,
            			smLimit:-1,mmLimit:-1,smSent:0,mmSent:0
            				};
            	depDS.addData(n,function(){
            		var nn = depTree.data.findById(n.pk);
            		var i = depTree.data.indexOf(nn);
            		depTree.startEditing(i);
            	});
            	
            }
        },
		{title:"编辑",
			icon:"icon_edit.png",
			click:"depTree.startEditing(depTree.getFocusRow());"},
		{title:"删除",
			icon:"icon_delete.png",
			click:function(){
				if(depTree.data.size()==1){
					isc.say("禁止删除所有记录，你可以选择编辑此记录");
					return;
				}
				depTree.removeSelectedData();
			}
		}
	]
});

isc.Window.create({//EXCEL导入窗口
    ID: "userImportWindow", title: "用户导入",height:"100%", width: '800',autoCenter: true, isModal: true, showModalMask: true, autoDraw: false,
    closeClick : function () {
    	this.Super("closeClick", arguments);
    	//depTree.invalidateCache();
    },
    items: [
		isc.BatchUploader.create({
			layoutMargin:15,partialCommitPrompt:"你的数据中有错误，所以不会被全部保存，如果您继续，有错误的记录将不会被导入。",
			uploadFormFields: [
			    { value: "user.xls", title:"模板下载",canEdit: false, type: "link" ,width:180}
			],
            uploadDataSource: user,uploadFileLabel:"Excel ",
            requestProperties:{willHandleError:true,operationId:"batchImport"},
            gridProperties: {height:350,width: '100%',addOperation:"batchImport"},
            gridFields :[
		        {name:"truename"},{name:"telephone"},{name:"password"},{name:"dep_pk"},{name:"sex"},
		        {name:"address"},{name:"certificateType"},{name:"certificateNum"}
		        ]
        })
    ]
});

isc.ListGrid.create({//用户列表
	ID:"userList",dataSource:"user",fetchOperation:"adminFetch",addOperation:"adminAdd",
	useAllDataSourceFields:true,showRowNumbers:true,canEdit:true, modalEditing:true,
    height:"100%",autoFetchData: true, showFilterEditor: true, selectionAppearance:"checkbox",
    selectionType:"simple",filterOnKeypress: true,
    canEditCell : function (rowNum, colNum) {
    	//管理员不能把自己设置为非管理员,不能修改自己部门
        var record = this.getRecord(rowNum);
        var fieldName = this.getFieldName(colNum);
        
        if(!record){
        	return this.Super("canEditCell", arguments);
        }
        if ((fieldName == "admin" || fieldName == "dep_pk")&& record.pk == currUserPK)  {
            return false;   
        }
        // use default rules for all other fields
        return this.Super("canEditCell", arguments);
    },
	fields:[
            {name:"dep_pk",optionDataSource:"depDS",title:"部门",
            	optionOperationId:"mySelectFetch" ,valueField:"pk",displayField:"name" }
            ]
});

isc.HLayout.create({//用户操作按钮
    autoDraw: false,
    layoutMargin: 3,
    membersMargin: 7,
    ID: "userButtonLayout", members: [
        isc.IButton.create({
            autoDraw: false,
            title: "增加人员",
            click:"userList.startEditingNew()"
        }),

        isc.IButton.create({
            autoDraw: false,
            title: "删除选中人员",
	    	click: function () {
	    		 if (userList.getSelectedRecord()) {
	    			 isc.confirm("确定要删除吗？","if(value) userList.removeSelectedData()");
	    		 }else{
    				 isc.say("请选择记录");
    			 }
	    	}
        }),
        isc.IButton.create({
        	title: "从EXCEL导入",click:"userImportWindow.show()"
        }),
        isc.IButton.create({
        	autoDraw: false,
        	title: "群发开通短信",
        	click: function () {
        		 var data = userList.getSelection(); 
	    		 if (data) {
	    				var wasQueuing1 = RPCManager.startQueue();
						for(var i = 0; i < data.length; i++){
							var d = data.get(i);
							if(d.smStatus === true){
								continue;
							}
							var task = {};
							task.mt_content="您好，贵公司管理员"+currUserTruename+"邀请您开通手机版功能，请回复Y同意开通。";
							task.mt_dst_num=d.telephone;
							task.mt_dst_name=d.truename;
							task.from_number=currUserTelephone;
							task.mt_dst_size=1;
							sms_task.addData(task);
						}
						if (!wasQueuing1) RPCManager.sendQueue(function(){
							isc.say("已保存到待发列表中！");
						});
	    		 }else{
	    			 isc.say("请选择记录");
   			    }
	    	}
        })
    ]
});
isc.HLayout.create({//组织结构应用布局
	ID:"orgLayout",
	width:"100%",
	height:"100%",
	members:[
		isc.SectionStack.create({
			width:180,
			sections:[
				{title:"组织结构", autoShow:true, items:[depTree]}
			]
		}),
		isc.SectionStack.create({
			sections:[
				{title:"人员", autoShow:true, items:[userButtonLayout,userList]}
			]
		})
	]
});


// 黑名单
// ---------------------------------------------------------------------
isc.HLayout.create({//黑名单按钮
	ID: "blackButtonLayout",autoDraw: false,layoutMargin: 3,membersMargin: 7,
    members: [
	    isc.IButton.create({title: "增加",click:"blackList.startEditingNew()"}),
	    isc.IButton.create({title: "删除选中",click:function(){
			 if (blackList.getSelectedRecord()) {
    			 isc.confirm("确定要删除吗？","if(value) blackList.removeSelectedData()");
    		 }else{
				 isc.say("请选择记录");
			 }
		}})
    ]
});
isc.ListGrid.create({//黑名单列表
	ID:"blackList",dataSource:"blackDS",addOperation:"depAdd",fetchOperation:"depFetch",
	useAllDataSourceFields:true,
	showRowNumbers:true,
	canEdit:true,
    modalEditing:true,
	alternateRecordStyles:true,
    height:"100%",
    autoFetchData: true,
    showFilterEditor: true,
    selectionAppearance:"checkbox",
    selectionType:"simple",
	filterOnKeypress: true
});
isc.HLayout.create({//应用布局
	ID:"blackApp",
	width:"100%",
	height:"100%",
	members:[
		isc.SectionStack.create({
			sections:[
				{title:"黑名单", autoShow:true, items:[ blackButtonLayout,blackList]}
			]
		})
	]
});


// 短信配额
// ---------------------------------------------------------------------
isc.SectionStack.create({ID:"appLimt",width:'100%',sections:[{title:"各部门短信配额",autoShow:true, items:[
    isc.DynamicForm.create({cellBorder :0,width:300,
    	 ID:"limitForm",dataSource:"companyDS",saveOperationType:"update",numCols:4,colWidths:[1,50,1,'*'],
    	fields:[
    	        {name:"corp_sid",value:currUserCorpSid,type:"hidden"},
    	        {name:"ms_limit",value:currComMsLimit,
    	        	changed:function (form, item, value){
    	        	form.saveData();
    	        }},
    	        {type:"staticText",value:'<div style="color:red">配额值为-1表示不限制</div>'}
    	]
    }),                                                                                     
	isc.TreeGrid.create({//配额树
		ID:"limitDepTree",dataSource:"depDS",fetchOperation:"myTreeFetch",canEdit: true,
		leaveScrollbarGap:true,animateFolders:true,loadDataOnDemand :true,
		showHeader:true,selectionType:"single",modalEditing:true,
		autoFetchData: true,
		dataArrived:function(parentNode){
			if(!parentNode.pk){
				//自动展开根节点
				this.openFolder(parentNode.children[0]);
				//部门管理员不能编辑本部门的总数
				if("depAdmin" == roles){
					parentNode.children[0].enabled=false;
				}
			}
		},
		fields: [
				 {name: "name",canEdit:false,width:260},
				 {name: "smLimit",emptyCellValue:"-1"
					 ,validators: [
					     {
			             type: "custom",
			             /*验证值是否超过某个父部门*/
			             condition: function(item, validator, value, record){
			            	 //本身为不限制值,直接返回true
			            	 var ivalue =  parseInt(value);
			            	 if(isNaN(ivalue) || ivalue == -1) return true;
			            	 
			            	 //找到有值有父部门
			            	 var p = limitDepTree.data.getParent(record);
			            	 while(p != null && (isNaN(p.smLimit) || p.smLimit == -1)){
			            		 p = limitDepTree.data.getParent(p);
			            	 }
			            	 //如果所有父部门都无限制,返回true
			            	 if(p == null ) return true;
			            	 
			            	 //比较最终值
			            	 if(ivalue > p.smLimit) return false;
			            	 else  return true;
			             },
			             errorMessage: "配额超出上级部门限制"
			         }]
				 },
				 {name: "smSent",canEdit:false,emptyCellValue:"0"},
				 {name: "mmLimit",emptyCellValue:"-1"
					 ,validators: [
								     {
						             type: "custom",
						             /*验证值是否超过某个父部门*/
						             condition: function(item, validator, value, record){
						            	 //本身为不限制值,直接返回true
						            	 var ivalue =  parseInt(value);
						            	 if(isNaN(ivalue) || ivalue == -1) return true;
						            	 
						            	 //找到有值有父部门
						            	 var p = limitDepTree.data.getParent(record);
						            	 while(p != null && (isNaN(p.mmLimit) || p.mmLimit == -1)){
						            		 p = limitDepTree.data.getParent(p);
						            	 }
						            	 //如果所有父部门都无限制,返回true
						            	 if(p == null ) return true;
						            	 
						            	 //比较最终值
						            	 if(ivalue > p.mmLimit) return false;
						            	 else  return true;
						             },
						             errorMessage: "配额超出上级部门限制"
						         }]
				 },
				 {name: "mmSent",canEdit:false,emptyCellValue:"0"}
			 ]
	})
]}]});

//短信配制
//---------------------------------------------------------------------
isc.SectionStack.create({ID:"smConfigApp",width:'100%',sections:[{title:"短信模板配制",autoShow:true, items:[
	isc.HLayout.create({layoutTopMargin: 3,membersMargin: 3,height:30,
		members: [
		    isc.IButton.create({title: "增加",click:"smConfigList.startEditingNew()"}),
		    isc.IButton.create({title: "删除选中",click:function(){
				 if (smConfigList.getSelectedRecord()) {
	    			 isc.confirm("确定要删除吗？","if(value) smConfigList.removeSelectedData()");
	    		 }else{
	    			 isc.say("请选择记录");
	    		 }
			}})
	    ]
	}),
	 isc.ListGrid.create({
		ID:"smConfigList",dataSource:"sms_config",fetchOperation:"comFetch",addOperation:"comAdd",showRowNumbers:false,
		canEdit:true, modalEditing:true, autoFetchData: true, showFilterEditor: true,
		filterOnKeypress: true,	wrapCells: true,cellHeight: 56, selectionType:"simple",selectionAppearance:"checkbox",
		fields:[
				{name:"title"}, 
				{name:"content",type:"text",showHover:true,
					cellChanged: function(record,value){
						record.mt_dst_size = Math.ceil(value.length/70);
						smConfigList.updateData(record);
					}
				},
				{name:"mt_dst_size",canEdit:false},
				{name:"inCallSend"},
				{name:"outCallSend"}
		]
	})
]}]});


//彩信配制
//---------------------------------------------------------------------
isc.Window.create({
  ID: "mmsConfigWindow", title: "彩信配制", width:'80%',height:'100%', autoCenter: true, isModal: true, showModalMask: true, autoDraw: false,
  closeClick : function () {
  	mmsConfigList.invalidateCache();
  	this.Super("closeClick", arguments);
  	this.animateMove(-3300);
  },
  items: [
		isc.HTMLPane.create({
		    ID:"mmsConfigPane",
		    showEdges:true,
		    contentsType:"page"
		})
  ]
});

isc.SectionStack.create({ID:"mmsConfigApp",width:'100%',
	sections:[{title:"彩信模板配制",autoShow:true, items:[
	  isc.HLayout.create({
	      autoDraw: false, layoutTopMargin: 3, membersMargin: 3, height:30,
	      members: [
	            isc.IButton.create({
	      		    title: "增加",
	      		    click:function(){
	      		    	mmsConfigPane.setContentsURL('mmsConfig.do?method=append&company=y');
	      		    	mmsConfigWindow.centerInPage();
	      		    	mmsConfigWindow.show();
	      		    }
	      	    }),
				isc.IButton.create({title: "删除选中",click:function(){
					 if (mmsConfigList.getSelectedRecord()) {
						 isc.confirm("确定要删除吗？","if(value) mmsConfigList.removeSelectedData()");
					 }else{
						 isc.say("请选择记录");
					 }
				}})
	      ]
	  }),
	  isc.ListGrid.create({
		ID:"mmsConfigList",selectionType:"simple",selectionAppearance:"checkbox",fetchOperation:"comMmsFetch",
		dataSource:"mms",useAllDataSourceFields:true,showRowNumbers:true,alternateRecordStyles:true,
	    autoFetchData: true, showFilterEditor: true,filterOnKeypress: true,wrapCells: true,
		fields:[
		   {name:"mms_subject",type:"link",target:"javascript"}
		   ,{name:"mms_size",width:50}
		   ,{name:"incoming_call_state",width:50
		   }
		   ,{name:"outcoming_call_state",width:50}
		   ,{name:"create_date",width:100}
		],
	    cellClick:function (record, rowNum, colNum){
	    	if(colNum == 2){
	    		mmsConfigPane.setContentsURL('');
	    		mmsConfigPane.setContentsURL('mmsConfig.do?method=edit&company=y&mmsSid='+record.mms_sid);
	    		mmsConfigWindow.centerInPage();
	    		mmsConfigWindow.show();
	    	}
	    }
	})
]}]});

